package cn.tedu._07weibopjt.controller;

import cn.tedu._07weibopjt.base.response.JsonResult;
import cn.tedu._07weibopjt.mapper.UserMapper;
import cn.tedu._07weibopjt.pojo.dto.UserLoginDTO;
import cn.tedu._07weibopjt.pojo.dto.UserRegDTO;
import cn.tedu._07weibopjt.pojo.entity.User;
import cn.tedu._07weibopjt.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

import static cn.tedu._07weibopjt.base.response.StatusCode.*;
@Slf4j
@RestController
@RequestMapping("/v1/users")
@Api (tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/reg")
    @ApiOperation(value = "注册用户", notes = "注册用户")
    @ApiImplicitParam(name = "userReg", value = "用户注册信息", required = true, dataType = "UserRegDTO")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userReg) {
        log.debug("注册用户"+userReg);
        if (userMapper.checkUserName(userReg.getUsername()) == null) {
            User user = new User();
            BeanUtils.copyProperties(userReg, user);
            user.setCreated(new Date());
            userMapper.regUser(user);
            return JsonResult.ok();
        } else {
            return new JsonResult(USERNAME_EXIST);
        }
    }

    @PostMapping("/login")
    @ApiOperation(value = "登录用户", notes = "登录用户")
    @ApiImplicitParam(name = "userLogin", value = "用户登录信息", required = true, dataType = "UserLoginDTO")
    public JsonResult login(@RequestBody UserLoginDTO userLogin,@ApiIgnore HttpSession session) {
        UserVO userVO = userMapper.checkUserName(userLogin.getUsername());
        if (userVO == null) return new JsonResult(USERNAME_ERROR);
        if (userVO.getPassword().equals(userLogin.getPassword())) {
            session.setAttribute("user", userVO); // 保存在服务器的内存中
            return JsonResult.ok(userVO);
        }
        return new JsonResult(PASSWORD_ERROR);
    }

    @GetMapping("/currentUser")
    @ApiOperation(value = "获取当前登录用户", notes = "获取当前登录用户")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出登录", notes = "退出登录")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }
}
